import { _decorator, Camera, Component, game, Node, Rect, UITransform, Vec3, view, Widget } from 'cc';
import { UIRootController } from './UIRootController';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('ViewportController')
@requireComponent(Camera)
export class ViewportController extends Component {
    private _camera: Camera = null!;

    protected onLoad(): void {
        this._camera = this.node.getComponent(Camera)!;
        game.on(UIRootController.Event.ROOT_SIZE_CHANGED, this._onRootSizeChanged, this);
        this._onRootSizeChanged();
    }

    protected onDestroy(): void {
        game.off(UIRootController.Event.ROOT_SIZE_CHANGED, this._onRootSizeChanged, this);
    }

    private _onRootSizeChanged(): void {
        const inst = UIRootController.instance;
        if (!inst || !inst.isRunning) return;
        const viewportWidth = inst.uiSize.width / inst.viewSize.width;
        const viewportHeight = inst.uiSize.height / inst.viewSize.height;
        const offsetX = (1 - viewportWidth) / 2;
        const offsetY = (1 - viewportHeight) / 2;
        this._camera.rect = new Rect(offsetX, offsetY, viewportWidth, viewportHeight);
    }
}


